import { useEffect, useRef, useCallback } from "react";
import * as echarts from "echarts";

interface RadarBarProps {
  id: number;
  name: string;
  value: number;
}

export default function RadarBar({
  radarData,
}: {
  radarData: RadarBarProps[];
}) {
  const radarTarget = useRef<HTMLDivElement>(null);

  const initEcharts = useCallback(() => {
    if (radarTarget.current && radarData.length > 0) {
      const myChart = echarts.init(radarTarget.current);
      const options = {
        radar: {
          color: "#05D5FF",
          fontSize: 14,
          shape: "polygon",
          center: ["50%", "50%"],
          radius: "80%",
          startAngle: 120,
          axisLine: {
            lineStyle: { color: "rgba(5,213,255,.8)" },
          },
          splitLine: {
            show: true,
            lineStyle: { width: 1, color: "rgba(5,213,255,.8)" },
          },
          indicator: radarData.map(({ name }) => ({ name, max: 100 })),
          splitArea: { show: false },
        },
        series: [
          {
            type: "radar",
            symbol: "circle",
            symbolSize: 10,
            itemStyle: { color: "#05D5FF" },
            areaStyle: { color: "#05D5FF", opacity: 0.5 },
            lineStyle: { width: 2, color: "#05D5FF" },
            label: {
              show: true,
              formatter: ({ value }: { value: number }) => value.toString(),
              color: "#fff",
            },
            data: [{ value: radarData.map(({ value }) => value) }],
          },
        ],
      };
      myChart.setOption(options);
    }
  }, [radarData]);

  useEffect(() => {
    initEcharts();
    const handleResize = () => initEcharts();
    window.addEventListener("resize", handleResize);
    const targetCurrent = radarTarget.current;
    return () => {
      window.removeEventListener("resize", handleResize);
      if (targetCurrent) {
        echarts.dispose(targetCurrent);
      }
    };
  }, [initEcharts]);

  return (
    <div className="h-1/3 box-border pb-4">
      <div className="text-2xl text-white">【云端报警风险】</div>
      <div ref={radarTarget} className="w-full h-full"></div>
    </div>
  );
}
